<?php
function hasChinese($str) {
return preg_match('/[\x{4e00}-\x{9fff}]/u', $str) === 1;
}
// 使用示例
$str1 = "Hello World";
$str2 = "你好 World";
$str3 = "こんにちは";
var_dump(hasChinese($str1)); // bool(false)
var_dump(hasChinese($str2)); // bool(true)
var_dump(hasChinese($str3)); // bool(false)
<?php
function hasChinese($str) {
// 包含基本汉字、扩展A区、兼容汉字等
return preg_match('/[\x{4e00}-\x{9fff}\x{3400}-\x{4dbf}\x{f900}-\x{faff}]/u', $str) === 1;
}
<?php
function isAllChinese($str) {
return preg_match('/^[\x{4e00}-\x{9fff}]+$/u', $str) === 1;
}
// 使用示例
var_dump(isAllChinese("你好")); // bool(true)
var_dump(isAllChinese("你好123")); // bool(false)
<?php
function getChinese($str) {
preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
return $matches[0];
}
// 使用示例
$str = "Hello 你好 World 世界";
$chinese = getChinese($str);
print_r($chinese); // Array([0] => 你好 [1] => 世界)
<?php
/**
* 判断字符串是否包含中文
* @param string $str 输入字符串
* @param bool $strict 是否使用严格模式(包含扩展区)
* @return bool
*/
function containsChinese($str, $strict = false) {
if ($strict) {
// 严格模式:包含基本汉字和扩展区
$pattern = '/[\x{4e00}-\x{9fff}\x{3400}-\x{4dbf}\x{f900}-\x{faff}]/u';
} else {
// 普通模式:仅基本汉字
$pattern = '/[\x{4e00}-\x{9fff}]/u';
}
return preg_match($pattern, $str) === 1;
}
// 测试
$testStrings = [
"Hello",
"你好",
"?", // 扩展区汉字
"Hello 你好",
"123"
];
foreach ($testStrings as $str) {
echo "$str: " . (containsChinese($str) ? "包含" : "不包含") . "中文\n";
echo "$str (严格): " . (containsChinese($str, true) ? "包含" : "不包含") . "中文\n\n";
}
说明: